export module HttpRequest {
    let ip = "https://www.keepmobi.com/ga/";

    /**
     * 
     * @param url 
     * @param node 
     * @param callBack 
     */
    export function updateHttpSprite(url: string, spr: cc.Sprite, callBack?) {
        if (url.indexOf("http") != -1) {
            try {
                cc.assetManager.loadRemote(url, { ext: headImgExt }, (error, res) => {
                    // console.log("回調會啊給你:", res, url)
                    let sprite = new cc.SpriteFrame(res as cc.Texture2D);
                    if (spr) spr.spriteFrame = sprite
                })
            } catch (error) {
                console.log("拉取图片失败!", error);
            }

        } else {
            return;
            url = "texture/head_icon/" + url;
            cc.resources.load(url, cc.SpriteFrame, (err, res: cc.SpriteFrame) => {
                if (err) {
                    console.error(url + ' not exist');
                    return;
                }
                spr.spriteFrame = res
                if (callBack) {
                    callBack()
                }
            });
        }
    }


    export const headImgExt = ".head";
    /**  * 新版本的cocos加载头像的时候，需要先下载，但是在字节小游戏平台下，会有跨域的问题。这个方法需要在进入游戏后加载前调用
    * 加载头像的用法:cc.assetManager.loadRemote(url,{ext:headImgExt},(err,texture)=>{});
    * 所有不想下载直接使用的图像都可以加上{ext:headImgExt}来使用  */
    export function registerHeadImgLoader() {
        cc.assetManager.downloader.register(headImgExt, (content, options, onComplete) => {
            onComplete(null, content);
        });
        cc.assetManager.parser.register(headImgExt, downloadDomImage);

        function createTexture(id, data, options, onComplete) {
            let out = null,
                err = null;
            try {
                out = new cc.Texture2D();
                out._uuid = id;
                out._nativeUrl = id;
                out._nativeAsset = data;
            } catch (e) {
                err = e;
            }
            onComplete && onComplete(err, out);
        } (cc.assetManager as any).factory.register(headImgExt, createTexture);
    }

    function downloadDomImage(url, options, onComplete) {
        const img = new Image();

        if (window.location.protocol !== 'file:') {
            img.crossOrigin = 'anonymous';
        }

        function loadCallback() {
            img.removeEventListener('load', loadCallback);
            img.removeEventListener('error', errorCallback);
            if (onComplete) {
                onComplete(null, img);
            }
        }

        function errorCallback() {
            img.removeEventListener('load', loadCallback);
            img.removeEventListener('error', errorCallback);
            if (onComplete) {
                onComplete(new Error(url));
            }
        }

        img.addEventListener('load', loadCallback);
        img.addEventListener('error', errorCallback);
        img.src = url;
        return img;
    }
}